import { useState } from 'react'

const useFileDownloader = () => {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState(null)

    const downloadFile = async (url) => {
        setLoading(true)
        setError(null)
        try {
            const response = await fetch(url)
            if (!response.ok) throw new Error('Network response was not ok')
            const blob = await response.blob()
            const downloadUrl = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = downloadUrl
            a.download = '' // 可以提供文件名，例如 'downloadedFile.pdf'
            document.body.appendChild(a)
            a.click()
            a.remove()
            window.URL.revokeObjectURL(downloadUrl)
        } catch (err) {
            setError(err.message)
            console.error('Download error:', err)
        }
        setLoading(false)
    }

    return { downloadFile, loading, error }
}
export default useFileDownloader